//
//  AlarmClockViewController.m
//  Run
//
//  Created by sxz on 16/4/11.
//  Copyright © 2016年 BetaTheta. All rights reserved.
//

#import "AlarmClockViewController.h"
#import "WeekCollectionViewCell.h"
#import "CoreDataManager.h"
#import "TimeData.h"
#import "DCPathButton.h"
@interface AlarmClockViewController ()<UIPickerViewDelegate, UIPickerViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource,DCPathButtonDelegate>



#define SCALEWIDTH [UIScreen mainScreen].bounds.size.width / 375.0
#define SCALEHEIGHT [UIScreen mainScreen].bounds.size.height / 667.0
@property (nonatomic, strong) CoreDataManager *coreDataManager;//数据库
@property (nonatomic, strong) UIPickerView *picker;//时间选择
@property (nonatomic, strong) NSMutableArray *hours; //小时数组
@property (nonatomic, strong) NSMutableArray *minutes;//分钟数组

@property (nonatomic, assign) NSInteger hour;
@property (nonatomic, assign) NSInteger minute;

@property (nonatomic, strong) NSMutableArray *weeks; //选定星期数组
@property (nonatomic, strong) NSArray *weeksArray; //星期数组
@property (nonatomic, strong) UILabel *colckType;//闹钟类型

@property (nonatomic, strong) DCPathButton *dcPathButton;



@end

@implementation AlarmClockViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.picker = [UIPickerView new];
    
    [self.view addSubview:_picker];
    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    
    // 删除所有本地推送
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
//    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    // CoreData路径
        NSLog(@"******%@", [self.coreDataManager applicationDocumentsDirectory]);

    self.weeksArray = @[@"星期一 ", @"星期二 ", @"星期三 ", @"星期四 ", @"星期五 ", @"星期六 ", @"星期日"];
    self.weeks = [NSMutableArray arrayWithCapacity:0];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    backImageView.userInteractionEnabled = YES;
    
    backImageView.image = [UIImage imageNamed:@"闹钟背景图"];
    backImageView.contentMode = UIViewContentModeScaleToFill;
    
    [self.view addSubview:backImageView];
    
    _picker.delegate = self;
    _picker.dataSource = self;
    _picker.frame = CGRectMake(0, 30, WIDTH, HEIGHT/3);
   _picker.backgroundColor = [UIColor colorWithRed:1.000 green:0.500 blue:0.000 alpha:0.579];
    _picker.showsSelectionIndicator = YES;
    

    self.hours = [NSMutableArray arrayWithCapacity:0];
    self.minutes = [NSMutableArray arrayWithCapacity:0];
    
    for (int i = 0; i < 24; i ++) {
        
        [_hours addObject:[NSString stringWithFormat:@"%0.2d",i]];
    }
    for (int i = 0; i < 60; i ++) {
        [_minutes addObject:[NSString stringWithFormat:@"%0.2d",i]];
    }
    
    [self.view addSubview:_picker];
    
    
    // 添加按钮
    UIButton *addTime = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [addTime setTitle:@"确定" forState:UIControlStateNormal];
    [addTime addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
    addTime.backgroundColor = [UIColor redColor];
    [self.view addSubview:addTime];
    
    
    
    [addTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX).offset(WIDTH / 4);
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.bottom.equalTo(@-100);
    }];
    
    addTime.layer.cornerRadius = 20;
    addTime.clipsToBounds = YES;
    
    addTime.titleLabel.font = [UIFont italicSystemFontOfSize:20];
    [addTime setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addTime.backgroundColor = [UIColor orangeColor];
    addTime.layer.borderWidth = 2;
    addTime.layer.borderColor = [[UIColor whiteColor] CGColor];
    
    
    // 取消按钮
    UIButton *returnTime = [UIButton buttonWithType:UIButtonTypeSystem];
    returnTime.frame = CGRectMake(0, 0, 100, 100);
    [returnTime setTitle:@"取消" forState:UIControlStateNormal];
    [returnTime addTarget:self action:@selector(returnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:returnTime];
    
    returnTime.layer.cornerRadius = 20 ;
    returnTime.clipsToBounds = YES;
    returnTime.titleLabel.font = [UIFont italicSystemFontOfSize:20];
    [returnTime setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    returnTime.backgroundColor = [UIColor orangeColor];
    returnTime.layer.borderWidth = 2;
    returnTime.layer.borderColor = [[UIColor whiteColor] CGColor];

    [self.view addSubview:returnTime];
    
    [returnTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX).offset(-WIDTH / 4);
        make.size.mas_equalTo(addTime);
        make.bottom.equalTo(@-100);
    }];

    // 星期选择CollectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    layout.itemSize = CGSizeMake(WIDTH / 7 - 10, WIDTH / 7 - 10);
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView *collectionView = [[UICollectionView alloc ] initWithFrame:CGRectMake(0, 300 * SCALEHEIGHT, WIDTH, WIDTH / 7) collectionViewLayout:layout];
    
    // 允许多选
    collectionView.allowsMultipleSelection = YES;
    
    collectionView.backgroundColor = [UIColor clearColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    [self.view addSubview:collectionView];
    
    // cell的重用池
    [collectionView registerClass:[WeekCollectionViewCell class] forCellWithReuseIdentifier:@"WeekCollectionViewCell"];
    
    UILabel *headLabel = [[UILabel alloc] init];
    headLabel.backgroundColor = [UIColor clearColor];
    headLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:headLabel];
    headLabel.text = [NSString stringWithFormat:@"Week:%@", _todayWeek];

    headLabel.textColor = [UIColor colorWithWhite:0.502 alpha:1.000];
    
    [headLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(collectionView.mas_top);
        make.width.offset(WIDTH);
        make.height.offset(50 * SCALEHEIGHT);
    }];
    
    
}




//取消点击事件
#pragma mark returnAction
- (void)returnAction:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    
    self.navigationController.navigationBarHidden = NO;
    
    self.navigationController.tabBarController.tabBar.hidden = NO;
    
}



#pragma mark UIPickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0)
        return 24 * SCALEHEIGHT * 100;
    else
        return 60 * SCALEHEIGHT * 100;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 60 * SCALEHEIGHT;
}

#pragma mark UIPickerViewDelegate Methods
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    if (!view){
        view = [[UIView alloc]init];
    }
    
    [[pickerView.subviews objectAtIndex:1] setHidden:TRUE];
    [[pickerView.subviews objectAtIndex:2] setHidden:TRUE];
    
    
    if (component == 0) {
        
        UILabel *hoursLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 16, 0, WIDTH * 3 / 8, 50 * SCALEHEIGHT)];
       
       
        hoursLabel.textAlignment = NSTextAlignmentCenter;
        
        hoursLabel.text = [NSString stringWithFormat:@"%@点", [_hours objectAtIndex:row % _hours.count]];
        
        
        [view addSubview:hoursLabel];
        
        return view;
    }
    else {
        
        UILabel *minutesLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 16, 0, WIDTH * 3 / 8, 50 * SCALEHEIGHT)];
        minutesLabel.backgroundColor = [UIColor clearColor];
        minutesLabel.textAlignment = NSTextAlignmentCenter;
        minutesLabel.text = [NSString stringWithFormat:@"%@分", [_minutes objectAtIndex:row % _minutes.count]];
        
        [view addSubview:minutesLabel];
        
        return view;
    }
    
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (component == 0) {
        _hour = [[_hours objectAtIndex:row % _hours.count] intValue];
    }
    if (component == 1) {
        _minute = [[_minutes objectAtIndex:row % _minutes.count] intValue];
    }
}

#pragma mark AddAction
- (void)addAction:(id)sender {
    
    //添加Action
    if (_weeks.count != 0) {
        
        NSMutableString *weekStr = [NSMutableString string];
        
        for (NSString *str in _weeks) {
            [weekStr appendString:str];
        }
        
        NSString *timeID = [NSString stringWithFormat:@"%ld-%ld-%@", _hour, _minute, weekStr];
        //判断是否已经存在此闹钟
        int isOK = 0;
        
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"TimeData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
        [fetchRequest setEntity:entity];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            NSLog(@"%@", error);
        }else{
            for (TimeData *tim in fetchedObjects) {
                if ([tim.timeID isEqualToString:timeID]) {
                    isOK = 1;
                }
            }
        }
        //不存在
        if (isOK == 0) {
            
            TimeData *timer = [NSEntityDescription insertNewObjectForEntityForName:@"TimeData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
            
            timer.type = self.colckType.text;
            
            timer.hour = [NSNumber numberWithInteger: _hour];
            
            timer.minte = [NSNumber numberWithInteger: _minute];
            
            timer.week = weekStr;
            
            timer.timeID = timeID;
            
            [_coreDataManager saveContext];
            
#pragma mark 发送本地通知
            
            if (_weeks.count == 7) {
                
                UILocalNotification *notification = [[UILocalNotification alloc] init];
                
                if (notification) {
                    
                    notification.fireDate = [NSDate dateWithTimeIntervalSince1970:(_hour - 8)*60*60 + _minute * 60];//本次开启立即执行的周期
                    notification.repeatInterval = kCFCalendarUnitDay;//每天都响
                    
                    // 提示信息
                    NSString *Time = [NSString stringWithFormat:@"时间到"];
                    notification.alertBody = Time;
                    NSString *Type = [NSString stringWithFormat:@"来事了啊"];
                    notification.alertAction = NSLocalizedString(Type, nil);
                    
                    //取消推送用的字典
                    NSDictionary * inforDic = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%ld-%ld-%@", _hour, _minute, weekStr] forKey:[NSString stringWithFormat:@"%ld-%ld-%@", _hour, _minute, weekStr]];
                    notification.userInfo =inforDic;
                    
                    // 添加到系统
                    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
                    NSLog(@"^^^^^^^^^^^^^^^^^^^^^^%@", [[UIApplication sharedApplication] scheduledLocalNotifications]);
                    
                }
                
            } else {
                for (NSString *weekString in _weeks) {
                    
                    UILocalNotification *notification = [[UILocalNotification alloc] init];
                    
                    if (notification) {
                        
                        int week;
                        
                        if ([weekString isEqualToString:@"星期四 "]) {
                            week = 0;
                        } else if ([weekString isEqualToString:@"星期五 "]) {
                            week = 1;
                        } else if ([weekString isEqualToString:@"星期六 "]) {
                            week = 2;
                        } else if ([weekString isEqualToString:@"星期日 "]) {
                            week = 3;
                        } else if ([weekString isEqualToString:@"星期一 "]) {
                            week = 4;
                        } else if ([weekString isEqualToString:@"星期二 "]) {
                            week = 5;
                        } else {
                            week = 6;
                        }
                        
                        int day = 24 * 60 * 60 * week;
                        
                        notification.fireDate = [NSDate dateWithTimeIntervalSince1970:(_hour - 8)*60*60 + _minute * 60 + day];//本次开启立即执行的周期
                        notification.repeatInterval = kCFCalendarUnitWeek;//每周都响
                        
//                        notification.soundName = [NSString stringWithFormat:@"%@.mp3", self.musicName];
                        ;
                        // 提示信息
                        NSString *Time = [NSString stringWithFormat:@"时间到了"];
                        notification.alertBody = Time;
                        NSString *Type = [NSString stringWithFormat:@"来事了啊"];
                        notification.alertAction = NSLocalizedString(Type, nil);
                        
                        //                        NSLog(@"%ld%ld", _hour, _minute);
                        
                        //取消推送用的字典
                        NSDictionary * inforDic = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%ld-%ld-%@-%@", _hour, _minute, weekStr, weekString] forKey:[NSString stringWithFormat:@"%@-%@", weekStr, weekString]];
                        notification.userInfo =inforDic;
                        
                        // 添加到系统
                        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
                        
                    }
                    
                }
                
            }
            
            
        }
        //闹钟已经存在
        else {
            UIAlertView *alartView = [[UIAlertView alloc]initWithTitle:nil message:@"此闹钟已经存在" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alartView show];
            
        }
        
        [self.navigationController popViewControllerAnimated:YES];
        
        self.navigationController.navigationBarHidden = NO;
        
        self.navigationController.tabBarController.tabBar.hidden = NO;
        
        
    } else {
        
        NSString *string = @"确定";
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:@"请选择星期" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *ok = [UIAlertAction actionWithTitle:string style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertC addAction:ok];
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
        
    }
    
}


#pragma mark item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 7;
}

#pragma mark 创建cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    WeekCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WeekCollectionViewCell" forIndexPath:indexPath];
    
    cell.weekLabel.text = self.weeksArray[indexPath.row];
    
    return cell;
}

#pragma mark cell的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 点击特效
    [UIView beginAnimations:@"animationID" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationRepeatAutoreverses:NO];
    
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:[collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath] cache:YES];
    
    [UIView commitAnimations];
    
    // 根据indexPath获取cell
    WeekCollectionViewCell *cell = (WeekCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    cell.weekLabel.backgroundColor = [UIColor orangeColor];
    [self.weeks addObject:self.weeksArray[indexPath.row]];
    
}

#pragma mark 取消点击的方法
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [UIView beginAnimations:@"animationID" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationRepeatAutoreverses:NO];
    
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:[collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath] cache:YES];
    
    [UIView commitAnimations];
    
    WeekCollectionViewCell *cell = (WeekCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.weekLabel.backgroundColor = [UIColor grayColor];
    
    [self.weeks removeObject:self.weeksArray[indexPath.row]];
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
